//
//  CommentInputView.m
//  DebugDemo
//
//  Created by XFB on 2019/1/11.
//  Copyright © 2019年 ZhouCheng. All rights reserved.
//

#import "CommentInputView.h"
#import "Masonry.h"

@interface CommentInputView () <UITextViewDelegate>

@end

@implementation CommentInputView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];

        [self addSubview:self.textView];
        [self addSubview:self.sendButton];
        [self addSubview:self.lineView];
        /// 给控件添加约束
        [self addViewMasonry];
    }
    return self;
}

- (CommentTextView *)textView
{
    if (nil == _textView) {
        _textView = [[CommentTextView alloc] init];
        _textView.placeholder = @"我也来说两句";
        _textView.placeholderColor = UIColorFromRGB(0xCCCCCC);
        _textView.font = [UIFont systemFontOfSize:16.0f];
        _textView.layer.masksToBounds = YES;
        _textView.layer.cornerRadius = 5.0f;
        _textView.returnKeyType = UIReturnKeySend;
        _textView.backgroundColor = RGB(238, 238, 238);
        _textView.delegate = self;
        _textView.scrollsToTop = NO;
    }
    return _textView;
}

- (UIButton *)sendButton
{
    if (nil == _sendButton) {
        _sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
        [_sendButton setTitleColor:UIColorFromRGB(0x1ABC9C) forState:UIControlStateNormal];
        _sendButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_sendButton addTarget:self action:@selector(sendButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendButton;
}

- (void)addViewMasonry
{
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self).mas_offset(-10);
        make.right.mas_equalTo(self).mas_offset(-10);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(30);
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self).mas_offset(7);
        make.bottom.mas_equalTo(self).mas_offset(-7);
        make.left.mas_equalTo(self).mas_offset(10);
        make.right.mas_equalTo(self.sendButton.mas_left).mas_offset(-10);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self).mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
}

- (void)sendButtonDidClick:(UIButton *)button
{
    NSLog(@"发送按钮点击");
}

#pragma mark --- <UITextViewDelegate>

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    /// 过滤特殊字符
    NSString *tempString = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
    if (![text isEqualToString:tempString]) {
        return NO;
    }
    
    /// 点击回车键 send
    if ([text isEqualToString:@"\n"]) {
        if (self.textView.text.length > 0) {
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(commentInputView:sendTextString:)]) {
                [self.delegate commentInputView:self sendTextString:self.textView.text];
            }
            
            self.textView.text = @"";
            /// 刷新textView的动画
            [self reloadTextViewWithAnimation:YES];
            
            return NO;
        }
    } else if (textView.text.length > 0 && [text isEqualToString:@""]) {

        if ([textView.text characterAtIndex:range.location] == ']') {
            NSInteger location = range.location;
            NSInteger length = range.length;
            
            while (location != 0) {
                location --;
                length ++;
                char c = [textView.text characterAtIndex:location];
                if (c == '[') {
                    textView.text = [textView.text stringByReplacingCharactersInRange:NSMakeRange(location, length) withString:@""];
                    /// 刷新textView的高度
                    [self reloadTextViewWithAnimation:YES];
                    return NO;
                } else if (c == ']') {
                    return YES;
                }
            }
        }
    }
    return YES;
}


- (void)reloadTextViewWithAnimation:(BOOL)animation
{
    /// 计算输入框文字的高度
    CGFloat textHeight = [self.textView sizeThatFits:CGSizeMake(self.textView.width, MAXFLOAT)].height;
    ///
    CGFloat tempHeight = textHeight > 36 ? textHeight : 36;
    tempHeight = (textHeight < 111.5 ? textHeight : 111.5);
    [self.textView setScrollEnabled:textHeight > tempHeight];

    if (tempHeight != self.textView.height) {
        if (animation) {
            [UIView animateWithDuration:0.25 animations:^{
                /// 重新更新输入框的u约束
                [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(tempHeight);
                }];
                
                if (self.superview) {
                    [self.superview layoutIfNeeded];
                }
                
                if (self.delegate && [self.delegate respondsToSelector:@selector(commentInputView:didChangeTextViewHeight:)]) {
                    [self.delegate commentInputView:self didChangeTextViewHeight:self.textView.height];
                }
            } completion:^(BOOL finished) {
               
                if (textHeight > tempHeight) {
                    [self.textView setContentOffset:CGPointMake(0, textHeight-tempHeight) animated:YES];
                }
                
                if (self.delegate && [self.delegate respondsToSelector:@selector(commentInputView:didChangeTextViewHeight:)]) {
                    [self.delegate commentInputView:self didChangeTextViewHeight:self.textView.height];
                }
            }];
        } else {
            /// 重新更新输入框的u约束
            [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(tempHeight);
            }];
            
            if (self.superview) {
                [self.superview layoutIfNeeded];
            }
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(commentInputView:didChangeTextViewHeight:)]) {
                [self.delegate commentInputView:self didChangeTextViewHeight:self.textView.height];
            }
            if (textHeight > tempHeight) {
                [self.textView setContentOffset:CGPointMake(0, textHeight-tempHeight) animated:YES];
            }
        }
    } else if (textHeight > tempHeight) {
        CGFloat offsetY = self.textView.contentSize.height - self.textView.height;
        if (animation) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.textView setContentOffset:CGPointMake(0, offsetY) animated:YES];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.textView setContentOffset:CGPointMake(0, offsetY) animated:NO];
            });
        }
    }
}

/// 结束编辑
- (void)textViewDidEndEditing:(UITextView *)textView
{
    [self reloadTextViewWithAnimation:YES];
}

/// 正在编辑
- (void)textViewDidChange:(UITextView *)textView
{
    [self reloadTextViewWithAnimation:YES];
}


@end


@implementation CommentTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange) name:UITextViewTextDidChangeNotification object:self];
}

- (void)textViewDidChange
{
    [self setNeedsDisplay];
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = [placeholder copy];
    [self setNeedsDisplay];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = [placeholderColor copy];
    [self setNeedsDisplay];
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    [self setNeedsDisplay];
}

- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    if (self.hasText) return;
    
    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
    attr[NSFontAttributeName] = [UIFont systemFontOfSize:15];
    attr[NSForegroundColorAttributeName] = self.placeholderColor ? self.placeholderColor : UIColorFromRGB(0xCCCCCC);
    /// 绘画占位文字
    CGFloat x = 5;
    CGFloat w = rect.size.width - 2 * x;
    CGFloat y = 10;
    CGFloat h = rect.size.height - 2 * y;
    CGRect placeholderRect = CGRectMake(x, y, w, h);
    [self.placeholder drawInRect:placeholderRect withAttributes:attr];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

@end
